﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Migrations.Model;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.XWPF.UserModel;

namespace ExportImportWord
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitDataBase();
        }

        public void InitDataBase()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlogModel>());
            var dbcontext = new BlogModel();
            var a = new ArticleInfo();
            a.Title = "hello";
            a.Content = "you see ,you can ,you can't do it";
            a.AddTime = "19871001";
            dbcontext.ArticleInfos.Add(a);
            dbcontext.SaveChanges();
            var source = dbcontext.ArticleInfos.ToList();
            dataGridViewArticle.DataSource = source;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var dbcontext = new BlogModel();
            var list = dbcontext.ArticleInfos.ToList();
            //创建document对象
            XWPFDocument doc = new XWPFDocument();
            //创建段落对象
            XWPFParagraph p1 = doc.CreateParagraph();
            //创建run对象
            //本节提到的所有样式都是基于XWPFRun的，
            //你可以把XWPFRun理解成一小段文字的描述对象，
            //这也是Word文档的特征，即文本描述性文档。
            //来自Tony Qu http://tonyqus.sinaapp.com/archives/609
            XWPFRun r1 = p1.CreateRun();
            r1.SetBold(true);
            r1.SetText("数据导出demo");
            r1.SetBold(true);
            r1.SetFontFamily("Arial");//设置雅黑字体
            //创建表格对象列数写死了，可根据自己需要改进或者自己想想解决方案
            XWPFTable table = doc.CreateTable(list.Count(), 4);
            for (int i = 0; i < list.Count(); i++)
            {
                table.GetRow(i).GetCell(0).SetText(list[i].Id.ToString());
                table.GetRow(i).GetCell(1).SetText(list[i].Title);
                table.GetRow(i).GetCell(2).SetText(list[i].Content);
                table.GetRow(i).GetCell(3).SetText(list[i].AddTime);
            }
            //保存文件到磁盘
            FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create);
            doc.Write(out1);
            out1.Close();
        }
    }
}
